<template>
  <div class="fillContainer">
    <ShopTitle :title="orderTitle" :activeIndex="orderIndex"></ShopTitle>
    <div class="order_title">收货人信息</div>
    <div class="order_info">
      <div class="info">{{ address_info }}</div>
      <div class="setinfo" @click="setAddress">立即设置</div>
    </div>
    <div class="order_title">订单详情</div>
    <ul v-for="item in BookArr" :key="item.shopcart_book_id">
      <li class="table_title">
        <div class="book_cover"></div>
        <div class="book_name">书名</div>
        <div class="book_yuanjia">原价</div>
        <div class="book_xianjia">售价</div>
        <div class="buy_num">购买数量</div>
        <div class="book_price">小计</div>
      </li>
      <li class="table_content">
        <div class="book_cover">
          <img :src="baseURL + item.book_cover" alt="" />
        </div>
        <div class="book_name" style="color:#d2ac6b">
          {{ item.book_name }}
        </div>
        <div class="book_yuanjia">￥{{ item.book_price_yuanjia }}</div>
        <div class="book_xianjia">￥{{ item.book_price_xianjia }}</div>
        <div class="buy_num">{{ item.num }}</div>
        <div class="book_price">￥{{ item.book_price_xianjia * item.num }}</div>
      </li>
      <li>
        <div class="express">
          <div class="express_left">
            卖家:<span style="color:#d2ac6b">{{ item.book_seller }}</span>
          </div>
          <div class="express_right">
            <div class="yunsong">
              <span>运送方式: 快递</span>
              <span style="font-weight:bold;">运费:￥{{ express_price }}</span>
            </div>
            <div class="yunfei">
              <span style="color:red;fontSize:14px;font-weight:bold;"
                >{{ item.num }}&nbsp;&nbsp;</span
              >本图书
              <span>店铺合计(含运费):</span>
              <span style="color:red;fontSize:14px;font-weight:bold;"
                >￥{{
                  towNumber(item.book_price_xianjia * item.num + express_price)
                }}</span
              >
            </div>
          </div>
        </div>
      </li>
    </ul>
    <div class="order_foot">
      <div class="pay">
        <div class="pay_info">
          实付款:
          <span style="color:red;fontSize:20px;font-weight:bold;"
            >￥{{ towNumber(total) }}</span
          >
        </div>
        <div class="order_button">
          <router-link to="/shopcart">
            <span style="color:#d2ac6b">&lt;返回购物车</span>
          </router-link>
          <el-button size="mini" @click="submitOrder">提交订单</el-button>
        </div>
      </div>
    </div>
    <!-- 设置收货地址弹窗 -->
    <el-dialog
      title="设置收货地址"
      :visible.sync="showSetAddress"
      width="50%"
      @close="SetAddressClose"
      :close-on-click-modal="false"
    >
      <!-- 注册表单 -->
      <el-form
        ref="addressFormRef"
        :model="addressForm"
        :rules="addressFormRules"
        label-width="80px"
      >
        <!-- 收货人 -->
        <el-form-item prop="consignee" label="收货人">
          <el-input v-model="addressForm.consignee"></el-input>
        </el-form-item>
        <!-- 手机号 -->
        <el-form-item prop="address_phone" label="手机号">
          <el-input v-model="addressForm.address_phone"></el-input>
        </el-form-item>
        <!-- 邮编 -->
        <el-form-item prop="postcode" label="邮编">
          <el-input v-model="addressForm.postcode"></el-input>
        </el-form-item>
        <!-- 省市区 -->
        <el-form-item prop="province" label="省市区">
          <el-cascader
            size="large"
            :options="options"
            v-model="selectedOptions"
            :value="addressForm.province"
            @change="handleChange"
          >
          </el-cascader>
        </el-form-item>
        <!-- 详细地址 -->
        <el-form-item prop="address" label="详细地址">
          <el-input type="textarea" v-model="addressForm.address"></el-input>
        </el-form-item>
        <!-- 按钮 -->
        <el-form-item class="btns">
          <el-button type="primary" @click="saveAddress">保存</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import ShopTitle from './ShopTitle.vue'
import { mapGetters } from 'vuex'
import { regionData, CodeToText } from 'element-china-area-data'
export default {
  components: {
    ShopTitle
  },
  data() {
    // 验证手机号码的规则
    var checkMobile = (rule, value, cb) => {
      const regMobile = /^1[34578]\d{9}$/
      if (regMobile.test(value)) {
        return cb()
      }
      // 返回一个错误提示
      cb(new Error('请输入合法的手机号码'))
    }
    return {
      // 获取勾选商品
      BookArr: [],
      baseURL: 'http://127.0.0.1:3000/',
      orderTitle: '填写订单',
      orderIndex: 2,
      // 运费
      express_price: 10,
      // 总价
      total: 0,
      // 设置地址弹窗
      // 地址信息
      address_info: '',
      // 全部地址信息
      address: '',
      showSetAddress: false,
      addressForm: {},
      addressFormRules: {
        consignee: [
          { required: true, message: '请填写收货人姓名', trigger: 'blur' }
        ],
        address_phone: [
          { required: true, message: '请填写手机号', trigger: 'blur' },
          {
            validator: checkMobile,
            message: '请输入正确的手机号',
            trigger: 'blur'
          }
        ],
        postcode: [{ required: true, message: '请填写邮编', trigger: 'blur' }],
        province: [
          { required: true, message: '请选择省市区', trigger: 'blur' }
        ],
        address: [
          { required: true, message: '请填写详细地址', trigger: 'blur' }
        ]
      },
      options: regionData,
      selectedOptions: []
    }
  },
  created() {
    console.log(this.$route.query.dataName, this.BookArr)
    if (this.BookArr.length == 0) {
      this.BookArr = this.$route.query.dataName
    }
    this.getAddress()
    this.getTotal()
  },
  methods: {
    // 提交订单
    async submitOrder() {
      console.log(this.address_info)
      if (this.address_info == '') {
        return this.$message.warning('请填写收货人信息')
      }
      this.BookArr.forEach(async item => {
        console.log(item)
        // 删除购物车商品
        // const { data: resDel } = await this.$http.post(
        //   '/shopcart/deleteShopCart',
        //   {
        //     username: this.getUser,
        //     book_id: item.shopcart_book_id
        //   }
        // )
        // if (resDel.code !== 200) {
        //   return this.$message.error('删除购物车信息失败')
        // }
        // 书本库存减少
        let bookNum = item.book_num - item.num
        const { data: resReduce } = await this.$http.put('/book/setBookNum', {
          book_id: item.shopcart_book_id,
          book_num: bookNum
        })
        if (resReduce.code !== 200) {
          return this.$message.error('更新库存失败')
        }
        // 提交订单
        let orderId = this.getProjectNum() + Math.floor(Math.random() * 10000)
        let orderPrice = item.book_price_xianjia * item.num + this.express_price
        const { data: res } = await this.$http.post('/order/addOrder', {
          order_id: orderId,
          order_buyer: this.address.consignee,
          order_date: this.getNowFormatDate(),
          order_price: orderPrice,
          order_seller: item.book_seller,
          order_status: 1,
          order_book_cover: item.book_cover,
          order_book_name: item.book_name,
          order_username: this.getUser,
          order_num: item.num
        })
        if (res.code !== 200) return this.$message.error('添加订单失败')
      })
      this.$router.push('/complete')
    },
    // 打开弹窗
    setAddress() {
      console.log(this.address)
      if (this.address !== '') {
        this.addressForm = this.address
        this.selectedOptions = this.address.province.split(',')
      }
      this.showSetAddress = true
    },
    // 关闭弹窗
    SetAddressClose() {},

    // 获取收货地址
    async getAddress() {
      const { data: res } = await this.$http.get(
        '/address/getAddress' + '/' + this.getUser
      )
      if (res.code !== 200) return
      if (res.data[0] !== undefined) {
        console.log(res.data[0])
        this.address = res.data[0]
        let arr = this.address.province.split(',')
        let data =
          CodeToText[arr[0]] +
          ', ' +
          CodeToText[arr[1]] +
          ', ' +
          CodeToText[arr[2]]
        this.address_info = data.replaceAll(',', '') + ' ' + res.data[0].address
      }
    },
    // 保存收货信息
    saveAddress() {
      this.$refs.addressFormRef.validate(async valid => {
        if (!valid) return
        // 如果已经有地址 则修改
        if (this.address !== '') {
          console.log(this.addressForm)
          const { data: updateRes } = await this.$http.put(
            '/address/updateAddress',
            {
              username: this.getUser,
              consignee: this.addressForm.consignee,
              address_phone: this.addressForm.address_phone,
              postcode: this.addressForm.postcode,
              province: this.selectedOptions.join(','),
              address: this.addressForm.address
            }
          )
          if (updateRes.code !== 200) return this.$message.error('保存地址失败')
          this.showSetAddress = false
          this.getAddress()
        } else {
          // 没有地址则添加
          const { data: addRes } = await this.$http.post(
            '/address/addAddress',
            {
              username: this.getUser,
              consignee: this.addressForm.consignee,
              address_phone: this.addressForm.address_phone,
              postcode: this.addressForm.postcode,
              province: this.selectedOptions.join(','),
              address: this.addressForm.address
            }
          )
          if (addRes.code !== 200) return this.$message.error('保存地址失败')
          this.$message.success('保存地址成功')
          this.showSetAddress = false
          this.getAddress()
        }
      })
    },
    // 省市区联动
    handleChange(value) {
      let data =
        CodeToText[value[0]] +
        ', ' +
        CodeToText[value[1]] +
        ', ' +
        CodeToText[value[2]]
      this.addressForm.province = data
      console.log(this.addressForm.province)
    },
    // 获取总价
    getTotal() {
      this.total = 0
      this.BookArr.forEach(item => {
        this.total += item.book_price_xianjia * item.num + this.express_price
      })
    },
    // 格式化价格 保留两位小数
    towNumber(val) {
      return val.toFixed(2)
    },
    // 获取当前日期的方法
    getProjectNum() {
      const projectTime = new Date() // 当前中国标准时间
      const Year = projectTime.getFullYear() // 获取当前年份 支持IE和火狐浏览器.
      const Month = projectTime.getMonth() + 1 // 获取中国区月份
      const Day = projectTime.getDate() // 获取几号
      var CurrentDate = Year
      if (Month >= 10) {
        // 判断月份和几号是否大于10或者小于10
        CurrentDate += Month
      } else {
        CurrentDate += '0' + Month
      }
      if (Day >= 10) {
        CurrentDate += Day
      } else {
        CurrentDate += '0' + Day
      }
      return CurrentDate
    }
  },
  computed: {
    ...mapGetters('user', ['getUser']),
    ...mapGetters('shopcart', ['getShoppingCart'])
  }
}
</script>

<style lang="scss" scoped>
.order_title {
  font-size: 20px;
  margin: 20px 0 2px 2px;
  padding-left: 4px;
  font-weight: bold;
  border-left: 4px solid rgb(0, 128, 128);
  color: #777;
}
.order_info {
  padding: 10px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #fff;
  color: #777;
  font-size: 12px;
  height: 20px;
  line-height: 20px;
  .setinfo {
    color: rgb(210, 172, 107);
    cursor: pointer;
  }
}
// 标题
.table_title {
  display: flex;
  height: 30px;
  line-height: 30px;
  background-color: #ccc;
  font-size: 14px;
  color: rgb(107, 107, 107);
  font-size: 12px;
}
// 内容
.table_content {
  display: flex;
  height: 65px;
  line-height: 65px;
  border-bottom: 1px solid #ccc;
  background-color: #fff;
  font-size: 12px;
  color: rgb(107, 107, 107);
}
.book_cover {
  width: 52px;
  img {
    width: 40px;
    height: 50px;
    border: 1px solid rgb(222, 222, 222);
    padding: 2px;
    vertical-align: middle;
    margin-right: 10px;
  }
}
.book_name {
  width: 510px;
}
.book_yuanjia {
  width: 109px;
}
.book_xianjia {
  width: 109px;
}
.buy_num {
  width: 109px;
}
.book_price {
  width: 109px;
}
// 运费
.express {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  height: 62px;
  background-color: #ebebeb;
  font-size: 12px;
  color: #777;
  .express_left {
    margin-top: 25px;
    margin-left: 10px;
  }
  .express_right {
    margin-top: 10px;
    .yunsong {
      display: flex;
      justify-content: space-between;
      height: 20px;
      line-height: 20px;
    }
    .yunfei {
      display: block;
      height: 30px;
      line-height: 30px;
      float: right;
    }
  }
}
/deep/ .el-radio__label {
  font-size: 10px;
}

.order_foot {
  margin-top: 10px;
  font-size: 12px;
  color: #777;
  display: flex;
  justify-content: flex-end;
  background-color: #fff;
  .pay {
    margin-top: 10px;
    .pay_info {
      display: block;
      text-align: right;
      margin-right: 17px;
    }
    .order_button {
      display: block;
      margin: 10px 0px;
      .el-button {
        margin: 0px 15px 0px 10px;
        background-color: rgb(210, 172, 107);
        color: #fff;
        font-size: 16px;
        font-weight: bold;
      }
    }
  }

  // 设置收货地址表单
}
</style>
